package com.sqx.modules.health.utils;/*
package com.sqx.modules.health.utils;

import com.github.wxpay.sdk.WXPayConstants;
import com.sqx.modules.health.config.WxConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.*;

import static com.github.wxpay.sdk.WXPayUtil.getLogger;

*/
/**
 * 微信工具类 统一下单、签名、生成随机字符串
 *//*

@Slf4j
public class WxUtil {

    // 导入微信SDK版本
    private static final String WXPAYSDK_VERSION = "WXPaySDK/3.0.10";

    //
    private static final String USER_AGENT = WXPAYSDK_VERSION +
            " (" + System.getProperty("os.arch") + " " + System.getProperty("os.name") + " " + System.getProperty("os.version") +
            ") Java/" + System.getProperty("java.version") + " HttpClient/" + HttpClient.class.getPackage().getImplementationVersion();

    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    // 随机数
    private static final Random RANDOM = new SecureRandom();


    public static Map<String, String> unifiedOrder(Map<String, String> reqData) throws Exception {
        // map格式转xml
        String reqBody = mapToXml(reqData);
        // 发起一次统一下单的请求
        String responseBody = requestOnce(WxConfig.payUrl, reqBody);
        // 将得到的结果由xml格式转为map格式
        Map<String, String> response = processResponseXml(responseBody);
        // 得到prepayId
        String prepayId = response.get("prepay_id");
        // 组装参数package_str 二次签名微信规定这样的格式
        String package_str = "prepay_id=" + prepayId;
        Map<String, String> payParameters = new HashMap<>();
        long epochSecond = Instant.now().getEpochSecond();
        payParameters.put("appId", WxConfig.appId); // 小程序APPID
        payParameters.put("nonceStr", WxUtil.generateNonceStr()); // 生成的32位随机字符串
        payParameters.put("package", package_str);// 返回的 prepay_id
        payParameters.put("signType", WXPayConstants.SignType.MD5.name()); // 签名的类型
        payParameters.put("timeStamp", String.valueOf(epochSecond));// 下单的时间戳
        // 二次签名
        payParameters.put("paySign", WxUtil.generateSignature(payParameters, WxConfig.key, WXPayConstants.SignType.MD5));
        // 返回签名后的map
        return payParameters;
    }
    public static Map<String, String>  appSendOrder(Map<String, String> reqData) throws Exception {
        // map格式转xml
        String reqBody = mapToXml(reqData);
        // 发起一次统一下单的请求
        String responseBody = requestOnce(WxConfig.payUrl, reqBody);
        // 将得到的结果由xml格式转为map格式
        Map<String, String> response = processResponseXml(responseBody);
        // 得到prepayId
        String prepayId = response.get("prepay_id");
        // 组装参数package_str 二次签名微信规定这样的格式
        String package_str = "prepay_id=" + prepayId;
        Map<String, String> payParameters = new HashMap<>();
        long epochSecond = Instant.now().getEpochSecond();
        payParameters.put("appId", WxConfig.appId); // 小程序APPID
        payParameters.put("nonceStr", WxUtil.generateNonceStr()); // 生成的32位随机字符串
        payParameters.put("package", package_str);// 返回的 prepay_id
        payParameters.put("signType", WXPayConstants.SignType.MD5.name()); // 签名的类型
        payParameters.put("timeStamp", String.valueOf(epochSecond));// 下单的时间戳
        // 二次签名
        payParameters.put("paySign", WxUtil.generateSignature(payParameters, WxConfig.key, WXPayConstants.SignType.MD5));
        // 返回签名后的map
        return payParameters;
    }
    */
/**
     * 判断签名是否有效
     *
     * @param xmlStr xml类型的字符
     * @return
     * @throws java.lang.Exception
     *//*

    private static Map<String, String> processResponseXml(String xmlStr) throws Exception {
        String RETURN_CODE = "return_code";
        String return_code;
        // 将 xml 转化为 map
        Map<String, String> respData = xmlToMap(xmlStr);
        // 判断map中是否存在 RETURN_CODE 属性
        if (respData.containsKey(RETURN_CODE)) {
            return_code = respData.get(RETURN_CODE);
        } else {
            throw new Exception(String.format("No `return_code` in XML: %s", xmlStr));
        }

        if (return_code.equals("FAIL")) {
            return respData;
        } else if (return_code.equals("SUCCESS")) {
            if (isResponseSignatureValid(respData)) {
                return respData;
            } else {
                throw new Exception(String.format("Invalid sign value in XML: %s", xmlStr));
            }
        } else {
            throw new Exception(String.format("return_code value %s is invalid in XML: %s", return_code, xmlStr));
        }
    }

    // 判断签名
    private static boolean isResponseSignatureValid(Map<String, String> data) throws Exception {
        String signKeyword = "sign";
        if (!data.containsKey(signKeyword)) {
            return false;
        }
        String sign = data.get(signKeyword);
        return generateSignature(data, WxConfig.key, WXPayConstants.SignType.MD5).equals(sign);
    }

    // 发起一次请求
    private static String requestOnce(String payUrl, String data) throws Exception {
        BasicHttpClientConnectionManager connManager;
        connManager = new BasicHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", SSLConnectionSocketFactory.getSocketFactory())
                        .build(),
                null,
                null,
                null
        );
        // 创建一个发起HTTP请求的客户端 发送HTTP请求
        HttpClient httpClient = HttpClientBuilder.create()
                .setConnectionManager(connManager)
                .build();
        HttpPost httpPost = new HttpPost(payUrl);

        // 设置请求超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(8000).setConnectTimeout(6000).build();
        httpPost.setConfig(requestConfig);
        // 设置请求体  请求方式 编码类型等
        StringEntity postEntity = new StringEntity(data, "UTF-8");
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.addHeader("User-Agent", USER_AGENT + " " + WxConfig.mchId);
        httpPost.setEntity(postEntity);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        // 获取到返回结果
        HttpEntity httpEntity = httpResponse.getEntity();
        // 将返回结果转化成UTF-8格式
        return EntityUtils.toString(httpEntity, "UTF-8");

    }

    */
/**
     * 生成一个随机32位字符串
     *
     * @return
     *//*

    public static String generateNonceStr() {
        char[] nonceChars = new char[32];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }

    */
/**
     * 生成签名. 注意，若含有sign_type字段，必须和signType参数保持一致。
     *
     * @param data     待签名数据
     * @param key      API密钥
     * @param signType 签名方式
     * @return 签名
     *//*

    public static String generateSignature(final Map<String, String> data, String key, WXPayConstants.SignType signType) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals("sign")) {
                continue;
            }
            if (data.get(k).trim().length() > 0) // 参数值为空，则不参与签名
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
        }
        sb.append("key=").append(key);
        if (WXPayConstants.SignType.MD5.equals(signType)) {
            return MD5(sb.toString()).toUpperCase();
        } else if (WXPayConstants.SignType.HMACSHA256.equals(signType)) {
            return HMACSHA256(sb.toString(), key);
        } else {
            throw new Exception(String.format("Invalid sign_type: %s", signType));
        }
    }

    */
/**
     * 生成 MD5
     *
     * @param data 待处理数据
     * @return MD5结果
     *//*

    private static String MD5(String data) throws Exception {
        // MessageDigest 用于为应用程序提供信息摘要算法的功能 规定生成规则位MD5
        MessageDigest md = MessageDigest.getInstance("MD5");
        // 使用UTF-8对摘要进行最后更新，然后完成摘要计算
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

    */
/**
     * map 转为 xml 格式
     *
     * @param data
     * @return
     * @throws java.lang.Exception
     *//*

    public static String mapToXml(Map<String, String> data) throws Exception {
        Document document = newDocument();
        Element root = document.createElement("xml");
        document.appendChild(root);
        for (String key : data.keySet()) {
            String value = data.get(key);
            if (value == null) {
                value = "";
            }
            value = value.trim();
            Element filed = document.createElement(key);
            filed.appendChild(document.createTextNode(value));
            root.appendChild(filed);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
        try {
            writer.close();
        } catch (Exception ex) {
        }
        return output;
    }

    private static String HMACSHA256(String data, String key) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

    */
/**
     * 解析xml
     *
     * @return
     * @throws javax.xml.parsers.ParserConfigurationException
     * @throws javax.xml.parsers.ParserConfigurationException
     *//*

    private static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException, ParserConfigurationException {
        // 创建DOM解析器的工厂
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        documentBuilderFactory.setXIncludeAware(false);
        documentBuilderFactory.setExpandEntityReferences(false);

        return documentBuilderFactory.newDocumentBuilder();
    }

    private static Document newDocument() throws ParserConfigurationException {
        return newDocumentBuilder().newDocument();
    }

    */
/**
     * xml 转 map
     *
     * @param strXML
     * @return
     * @throws java.lang.Exception
     *//*

    public static Map<String, String> xmlToMap(String strXML) throws Exception {
        try {
            Map<String, String> data = new HashMap<String, String>();
            DocumentBuilder documentBuilder = newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                // do nothing
            }
            return data;
        } catch (Exception ex) {
            getLogger().warn("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(), strXML);
            throw ex;
        }

    }

    */
/**
     * 判断签名是否正确
     *
     * @param xmlStr XML格式数据
     * @param key    API密钥
     * @return 签名是否正确
     * @throws java.lang.Exception
     *//*

    public static boolean isSignatureValid(String xmlStr, String key) throws Exception {
        Map<String, String> data = xmlToMap(xmlStr);
        if (!data.containsKey("sign")) {
            return false;
        }
        String sign = data.get("sign");
        return generateSignature(data, key, WXPayConstants.SignType.MD5).equals(sign);
    }

}
*/
